package com.hxzy.wx.controller;

import cn.hutool.Hutool;
import cn.hutool.core.io.IoUtil;
import com.hxzy.common.exception.HxdsException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.tags.Tags;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @Author wy
 * @Description TODO
 * @Date 2023/12/20 16:01
 * @Version 1.0
 */

@RestController
@RequestMapping("/voice")
@Log4j2
@Tag(name = "WxVoiceController", description = "音频下载API")
public class WxVoiceController {

     @Operation(summary = "声音文件(1-5)")
     @GetMapping(value = "/{num}")
     public void voice(@PathVariable(value = "num") Integer num, HttpServletResponse response) throws IOException {
         if(!(num>=1 && num<=5)){
             throw new HxdsException("音频文件请求不存在");
         }

         response.setContentType("audio/mpeg");
         response.setCharacterEncoding("utf-8");
         response.setHeader("Content-disposition", "attachment;filename*=utf-8''voice_" + num + ".mp3");

         //读文件流，放到response输出流中 ( io 操作)
         InputStream resourceAsStream = WxVoiceController.class.getResourceAsStream("/static/voice/voice_" + num + ".mp3");
         //输出流
         ServletOutputStream outputStream = response.getOutputStream();

         byte[] dataBuff=new byte[1024*8];
         int index=0;
         while( (index= resourceAsStream.read(dataBuff))!=-1){
             outputStream.write(dataBuff,0,index);
         }
         //关闭输入流
         resourceAsStream.close();
         //关闭输出流
         outputStream.flush();
         outputStream.close();
     }

}
